package com.batchbrake.main;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SrtUtils {
	public static EFile bufSrt = null;
	public static String[] bufContent = null;
	
	/**
	 * Search for the subtitles of the given movies
	 * @param files The list of files that are in the same folder as the movie
	 * @param movie The movie for which we want the SRT
	 * @return A List of File objects
	 */
	public static List<EFile> searchSrtFiles(EFile movie) {
		EFile[] files = movie.getParentEFile().listEFiles();
		List<EFile> srts = new ArrayList<EFile>();
		String basename = movie.getBaseName();
		for( int i = 0; i < files.length; i++ ) {
			if( files[i].getName().startsWith(basename) && files[i].getExtension().equals("srt") ) {
				srts.add(files[i]);
			}
		}
		return srts;
	}
	
	public static String guessLangOfSrtFile(EFile srt) throws IOException {
		EFile[] langs = new EFile("lang/").listEFiles();
		Integer[] scores = new Integer[langs.length];
		
		for( int i = 0; i < langs.length; i++ ) {
			scores[i] = 0;
			if( langs[i].isFile() ) {
				BufferedReader reader = new BufferedReader(new FileReader(langs[i]));
				String line = null;
				while( (line = reader.readLine()) != null ) {
					if( SrtUtils.srtFileContains(srt, line) ) {
						scores[i]++;
					}
				}
			}
		}
		
		int bestScore = Integer.MIN_VALUE;
		int bestScoreIndex = -1;
		for( int i = 0; i < scores.length; i++ ) {
			if( scores[i] > bestScore ) {
				bestScore = scores[i];
				bestScoreIndex = i;
			}
		}
		return langs[bestScoreIndex].getBaseName();
	}
	
	public static boolean srtFileContains(EFile srt, String word) throws IOException {
		if( (bufSrt == null) || !bufSrt.equals(srt) ) {
			BufferedReader reader = new BufferedReader(new FileReader(srt));
			String line = null;
			String content = "";
			
			while( (line = reader.readLine()) != null ) {
				content += line + "\n";
			}
			reader.close();
			bufSrt = srt;
			bufContent = content.split(" ");
		}

		for( int i = 0; i < bufContent.length; i++ ) {
			if( bufContent[i].equalsIgnoreCase(word) ) {
				return true;
			}
		}
		return false;
	}
}
